<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;

class SettingsController extends Controller
{
//    public function __construct()
//    {
//        $this->middleware('auth');
//    }

    public function index(Request $request)
    {
        $url = $request->input('uri','http://sso.zihaiyun.cc');
        $token = $request->cookie('token');
        if (\Cache::has($token)){
            return redirect($url.'?token='.$token);
        }
        return view('login');
    }

    public function loginHandle(Request $request)
    {
        $url = $request->input('uri','http://client.zihai.cc');
        $loginData = [
            'name' => $request->input('username'),
            'password' => $request->input('password')
        ];
        $user = \Auth::attempt($loginData);
        $token = Session::getId();
        \Cache::set($token,\Auth::user(),Carbon::now()->addHours(2));
        return redirect($url.'?token='.$token)->cookie('token',$token,3600);
     }

    public function reg()
    {

        return view('reg');
    }

     //注册
    public function register(Request $request)
    {
        $data =[
            'name' => $request->input('username'),
            'password' => bcrypt($request->input('password'))
        ];
        User::create($data);
        return view('login');
     }

     // 二次鉴权
    public function checkLogin(Request $request)
    {

        if (\Cache::has($request->input('token'))){
            return response()->json([
                'code' => 200,
                'user' => \Cache::get($request->input('token'))
            ]);
        }else{
            return response()->json([
                'code' => 401,
                'user' =>\Cache::get('token')
            ]);
        }
    }

    public function logout(Request $request)
    {
        $token = $request->input('token');
        \Cache::forget($token);
        \Auth::logout();
        return response()->json([
            'code' => 200,
            'message' => 'ok'
        ]);

    }
}
